<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: Beansdb 图片存储
 *
 * @author      Eden
 * @datetime    2016/12/6 09:32
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Beansdb
{
    /**
     * @var CI_Controller|null
     */
    private $ci = null;

    /**
     * @var array 配置
     */
    private $config = array(
        'host' => '127.0.0.1',
        'port' => 7900,
    );

    /**
     * 初始化
     */
    public function __construct()
    {
        $this->ci = &get_instance();
        $this->ci->config->load('beansdb');
        $conf = $this->ci->config->item('beansdb');
        if (!empty($conf)){
            $this->config = $conf;
        }
    }

    /**
     * 获取 Beansdb 对象
     * @return Memcache|null
     */
    protected function getResource()
    {
        $host = value($this->config, 'host');
        $port = value($this->config, 'port');
        if (empty($host) || empty($port)) {
            return null;
        }

        try {
            $mem = new Memcache();
            $mem->connect($host, $port);
            return $mem;
        } catch(Exception $e) {
            return null;
        }
    }

    /**
     * 保存
     * @param $key
     * @param $data
     * @return array|bool
     */
    public function save($key, $data)
    {
        try {
            $mem = $this->getResource();
            return $mem->set($key, $data);
        } catch(Exception $e) {}
        return false;
    }

    /**
     * 值是否存在
     * @param $key
     * @return bool
     */
    public function has($key)
    {
        try {
            $mem = $this->getResource();
            $data = $mem->get($key);
            return !empty($data) ? true : false;
        } catch(Exception $e) {
            echo $e->getMessage();
        }
        return false;
    }

    /**
     * 取数据
     * @param $key
     * @return array|string
     */
    public function get($key)
    {
        try {
            return $this->getResource()->get($key);
        } catch(Exception $e){}
    }

    /**
     * 删
     * @param $key
     * @return bool
     */
    public function remove($key)
    {
        try {
            $mem = $this->getResource();
            return $mem->delete($key);
        } catch(Exception $e) {}
    }

}
